package per.turtle.system.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import per.turtle.common.core.utils.SecurityUtils;
import per.turtle.common.core.utils.ServletUtils;
import per.turtle.common.core.web.controller.BaseController;
import per.turtle.common.core.web.entity.CommonResult;
import per.turtle.common.log.annotation.Log;
import per.turtle.common.log.enums.BusinessType;
import per.turtle.common.security.service.TokenService;
import per.turtle.system.dto.LoginUser;
import per.turtle.system.dto.SysFile;
import per.turtle.system.entity.SysUser;
import per.turtle.system.feign.RemoteFileService;
import per.turtle.system.service.ISysUserService;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author turtle
 */
@AllArgsConstructor
@Api(value = "userProfile", tags = {"userProfile_个人信息管理模块"})
@RequestMapping("user/profile")
@RestController
public class SysProfileController extends BaseController {

    private final ISysUserService userService;

    private final TokenService tokenService;

    private final RemoteFileService remoteFileService;

    @ApiOperation(value = "头像上传", notes = "头像上传")
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("avatar")
    public CommonResult<Void> avatar(@RequestPart MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            CommonResult<SysFile> fileResult = remoteFileService.upload(file,true);
            if (BeanUtil.isEmpty(fileResult) || BeanUtil.isEmpty(fileResult.getData())) {
                return CommonResult.error("文件服务异常，请联系管理员");
            }
            String url = fileResult.getData().getUrl();
            SysUser user = new SysUser();
            user.setAvatar(url);
            user.setUserId(loginUser.getUserId());
            if (userService.updateUserAvatar(user)) {
                CommonResult<Void> result = CommonResult.success();
                Map<String, Object> map = new HashMap<>(2);
                map.put("imgUrl", url);
                result.setMap(map);
                // 更新缓存用户头像
                loginUser.getSysUser().setAvatar(url);
                tokenService.setLoginUser(loginUser);
                return result;
            }
        }
        return CommonResult.error("上传图片异常，请联系管理员");
    }

    @ApiOperation(value = "获取个人信息", notes = "获取个人信息")
    @GetMapping
    public CommonResult<SysUser> profile() {
        String username = SecurityUtils.getUsername();
        SysUser user = userService.selectUserByUserName(username);
        CommonResult<SysUser> result = CommonResult.success(user);
        // 角色，岗位
        Map<String, Object> map = new HashMap<>(2);
        map.put("roleGroup", userService.selectUserRoleGroup(username));
        map.put("postGroup", userService.selectUserPostGroup(username));
        result.setMap(map);
        return result;
    }

    @ApiOperation(value = "修改用户个人信息", notes = "修改用户个人信息")
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("edit")
    public CommonResult<Void> updateProfile(@RequestBody SysUser user) {
        if (StrUtil.isNotEmpty(user.getPhoneNumber()) && !userService.checkPhoneUnique(user)) {
            return CommonResult.error("修改用户【" + user.getUserName() + "】失败，手机号码已存在");
        } else if (StrUtil.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return CommonResult.error("修改用户【" + user.getUserName() + "】失败，邮箱账号已存在");
        }
        if (userService.updateUserProfile(user) > 0) {
            LoginUser loginUser = tokenService.getLoginUser();
            // 更新缓存用户信息
            loginUser.getSysUser().setNickName(user.getNickName());
            loginUser.getSysUser().setPhoneNumber(user.getPhoneNumber());
            loginUser.getSysUser().setEmail(user.getEmail());
            loginUser.getSysUser().setSex(user.getSex());
            tokenService.setLoginUser(loginUser);
            return CommonResult.success();
        }
        return CommonResult.error("修改个人信息异常，请联系管理员");
    }

    @ApiOperation(value = "重置密码", notes = "重置密码")
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("updatePwd")
    public CommonResult<Void> updatePwd(String oldPassword, String newPassword) {
        String username = SecurityUtils.getUsername();
        SysUser user = userService.selectUserByUserName(username);
        String password = user.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            return CommonResult.error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return CommonResult.error("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(username, SecurityUtils.encryptPassword(newPassword)) > 0) {
            // 更新缓存用户密码
            LoginUser loginUser = tokenService.getLoginUser();
            loginUser.getSysUser().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return CommonResult.success();
        }
        return CommonResult.error("修改密码异常，请联系管理员");
    }

}
